﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragLeDi : MonoBehaviour {

    private Vector3 _TargetScreenSpace;
    private Vector3 _TargetWorldSpace;
    private Transform _battery_transform;
    private Vector3 _MouseScreenSpace;
    private Vector3 _Offset;

    private Camera ui_Camera;
    private Vector3 _mousepos;
    private float dis;
    private float timer = 0;


    void Awake()
    {
        _battery_transform = transform;
        ui_Camera = WindowManager.Instance.camera;
        dis = 20f;
        Debug.LogError(ui_Camera);


    }


    // Update is called once per frame
    void Update()
    {
        timer += Time.deltaTime;
        if (_MouseScreenSpace != null && timer >= 0.1f)
        {
            if (_MouseScreenSpace.y - _mousepos.y < -dis)
            {
                this.transform.rotation = Quaternion.Euler(-15f, 0, 0);
            }
            if (_MouseScreenSpace.y - _mousepos.y >= dis)
            {
                this.transform.rotation = Quaternion.Euler(15f,0,0);
            }
            if (_mousepos == null || (_MouseScreenSpace.y - _mousepos.y < dis && _MouseScreenSpace.y - _mousepos.y > -dis))
            {
                this.transform.rotation = Quaternion.Euler(0f, 0, 0);
            }
           
            _mousepos = _MouseScreenSpace;
            timer = 0;
        }
    }

    IEnumerator OnMouseDown()

    {

        _TargetScreenSpace = ui_Camera.WorldToScreenPoint(_battery_transform.position);

        _MouseScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, _TargetScreenSpace.z);

        _Offset = _battery_transform.position - ui_Camera.ScreenToWorldPoint(_MouseScreenSpace);

        while (Input.GetMouseButton(0))
        {

            _MouseScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, _TargetScreenSpace.z);

            _TargetWorldSpace = ui_Camera.ScreenToWorldPoint(_MouseScreenSpace) + _Offset;

            _battery_transform.position = _TargetWorldSpace;

            yield return new WaitForFixedUpdate();
        }
    }




}
